package com.wontube.smr.bo.pub.filters;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

public class XmlFilterInputStreamReader extends InputStreamReader {
	private static final int replaceChar = '#';// 非法字符用#代替

	public XmlFilterInputStreamReader(InputStream in, String charsetName)
			throws UnsupportedEncodingException {
		super(in, charsetName);
	}

	public int read() throws IOException {
		int ch = super.read();
		if (ch > 0x1f) {
			return ch;
		}
		
		if (ch == 0x0d || ch == -1 || (ch > 0x08 && ch < 0x0b)) {
			return ch;
		}
		
		return replaceChar;
	}

	public int read(char cbuf[], int offset, int length) throws IOException {
		int count = super.read(cbuf, offset, length);
		for (int i = 0; i < count; i++) {
			if (cbuf[i] > 0x1f) {
				continue;
			}
			if (cbuf[i] == 0x0d || cbuf[i] == -1
					|| (cbuf[i] > 0x08 && cbuf[i] < 0x0b)) {
				continue;
			}
			
			cbuf[i] = replaceChar;
		}
		
		return count;
	}
}